﻿using UnityEngine;
using System.Collections;

public class PlayerManager : MonoBehaviour {
	public Navigator nav;
	public Node[] Path = null;
    public MapExplorer explorer;
	public int Next = 1;
	public bool Walking = false;
	public Node ActualNode;
	public bool Turn = false;
    public Stats stats;
    
    void Start() {
        stats = gameObject.GetComponent<Stats>();
        explorer = gameObject.GetComponent<MapExplorer>();
        stats.InitStats();
        stats.CalculateStats();
    }
	void FixedUpdate(){
		if (Path.Length > 0 && Walking && Turn) {
			if(Path[Next].NPCWalcable){
				if (Path [Next].Pos != gameObject.transform.position) {
                    transform.LookAt(Path[Next].Pos);
					transform.position = Vector3.MoveTowards (transform.position, Path [Next].Pos, Time.deltaTime*10);	
				} else {
                    explorer.RefreshAllVisuals();
					if (Next < Path.Length-1){
                            nav.StartNode = nav.mapa.theMap.Tiles[(int)transform.position.x, (int)transform.position.z].GetComponentInChildren<Node>();
							Next++;
					}else{
						Walking = false;
						ActualNode = Path[Next];
						nav.mapa.theMap.Tiles [(int)transform.position.x, (int)transform.position.z].GetComponentInChildren<Node> ().NPCWalcable = false;
						Turn = false;
					}
				}
			}else{
				Walking = false;
				ActualNode = Path[Next];
				nav.mapa.theMap.Tiles [(int)transform.position.x, (int)transform.position.z].GetComponentInChildren<Node> ().NPCWalcable = false;
				Turn = false;
			}
		}
	}
	public void Init(Vector3 start){
        stats = gameObject.GetComponent<Stats>();
        explorer = gameObject.GetComponent<MapExplorer>();
        stats.InitStats();
        stats.CalculateStats();
		gameObject.transform.position = start;
        Walking = false;
	}
	public void GoToPos(Node t){
		Next = 0;
		Path = nav.GetPathToDestiny (t);
	}
    public void UnlockAtualNode() {
        nav.mapa.theMap.Tiles[(int)transform.position.x, (int)transform.position.z].GetComponentInChildren<Node>().NPCWalcable = true;
    }
    public void Shoot() {
       gameObject.GetComponent<Inventory>().equipedGun.Shoot(transform.position);
    }
}
